import Logger from '../base/logger';

async function fetchApi(url, data = {}, method = 'get', way = 'fetch') {
    method = method.toUpperCase();
    if (method === 'GET') {
        let str = '';
        Object.keys(data).forEach(item => {
            str += `${item}=${data[item]}&`;
        });
        if (str) {
            url = url + '?' + str.slice(0, -1);
        }
    }

    if (window.fetch && way === 'fetch') {
        let reqInit = {
            method,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
        };
        if (method === 'POST' || method === 'PATCH') {
            Object.assign(reqInit, {
                body: JSON.stringify(data)
            })
        }
        try {
            const res = await fetch(url, reqInit);
            Logger.info('url:', url, 'response=', res, 'at=', new Date());
            Logger.info(res.json());
            return res;
        } catch (e) {
            Logger.error(e);
            Promise.reject(e);
        }
    } else {
        return new Promise((resolve, reject) => {
            let httpReqObj;
            if (window.XMLHttpRequest) {
                httpReqObj = new XMLHttpRequest();
            } else {
                // eslint-disable-next-line no-undef
                httpReqObj = new ActiveXObject('Microsoft.XMLHTTP');
            }
            httpReqObj.open(method, url, true);
            httpReqObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            httpReqObj.send(method === 'POST' ? JSON.stringify(data) : null);
            httpReqObj.onreadystatechange = () => {
                if (httpReqObj.readyState === 4) {
                    if (httpReqObj.status === 200) {
                        let obj = httpReqObj.response;
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj);
                        }
                        resolve(obj);
                    } else {
                        reject(httpReqObj);
                    }
                }
            }
        })
    }
}

export {
    fetchApi
}